using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Linq;
using Accountant.DataModel;
using Caliburn.Micro;
using Accountant.Utils;

namespace Accountant.ViewModels
{
  [Export, PartCreationPolicy(CreationPolicy.NonShared)]
  public class EditingViewModel : PropertyChangedBase, IPartImportsSatisfiedNotification
  {
    [Import]
    public AccountantContext Data { get; set; }
    
    public ObservableCollection<Transaction> Transactions { get; private set; }

    #region ' Editor '

    private PropertyChangedBase _editor;

    public PropertyChangedBase Editor
    {
      get { return _editor; }
      private set
      {
        if (Equals(value, _editor)) return;
        _editor = value;
        NotifyOfPropertyChange(() => Editor);
      }
    }

    #endregion

    #region ' SelectedTransaction '

    private Transaction _selectedTransaction;

    public Transaction SelectedTransaction
    {
      get { return _selectedTransaction; }
      set
      {
        if (Equals(value, _selectedTransaction)) return;
        _selectedTransaction = value;
        NotifyOfPropertyChange(() => SelectedTransaction);

        if (_selectedTransaction != null)
        {
          if (_selectedTransaction.IsExpense())
          {
            Editor = new EditOperationViewModel(
              Data, _selectedTransaction, TransactionDirection.Expense);
          }
          else if (_selectedTransaction.IsIncome())
          {
            Editor = new EditOperationViewModel(
              Data, _selectedTransaction, TransactionDirection.Income);
          }
          else if (_selectedTransaction.IsTransfer())
          {
            Editor = new EditOperationViewModel(
              Data, _selectedTransaction, TransactionDirection.Transfer);
          }
        }
      }
    }


    #endregion

    void IPartImportsSatisfiedNotification.OnImportsSatisfied()
    {
      Transactions = new ObservableCollection<Transaction>(
        Data.Transactions.Where(t => !t.IsRevisioned()).OrderBy(t => t.Timestamp));
    }
  }
}